<?php

namespace backend\controllers;

use Yii;
use backend\models\Config;
use backend\models\ConfigSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * ConfigController implements the CRUD actions for Config model.
 */
class ConfigController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['set-theme','index'],
                        'allow' => true,
                        'roles' => ['@'], //@ 认证用户  ？ 游客 
                    ],
                ],
            ],
            
            
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
    
   

    /**
     * Lists all Config models.
     * @return mixed
     */
    public function actionIndex()
    {
        
        // 模型 
        $model = new Config();
        
        //当前配置 列表
        $configs = $this->getConfigList();
        $color_style = $this->getColorStyle();
        
        
        if(Yii::$app->request->isPost){
            
            $post = Yii::$app->request->post();

            foreach($post['config'] as $k=>$v){

                $model->updateAll(['value'=>$v],["name"=>$k]);
                    
            }
           
            
            return $this->redirect(array('config/index','data'=>$configs,'color_style'=>$color_style));
            
        }
        
        
        $searchModel = new ConfigSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
      
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'data' => $configs,
            'color_style' => $color_style,

        ]);
    }

    /*
     *   配置
     * 
     * 
     * 
     * **/
    
    /*
     *  获取 COLOR_STYLE
     * 
     * 
     * **/
    
    public function  getColorStyle(){
        
          //查询 设置
        $model = new Config();
        
        $configList = $model->find()->andWhere(['name'=>'COLOR_STYLE'])->asArray()->one();
        
        $color_style_str = $configList['extra'];
        
        $color_style_arr  = array();
        
        $color_arr = explode("\n", $color_style_str);
        
        foreach($color_arr as $v){
            
            $temp  = explode(":", $v);
            $color_style_arr[] = $temp;
        }
        
        return $color_style_arr;
        
    }
    
    /*
     *  获取 配置表列表 
     *   
     *  返回 array(
     *          name=>value,
     *   )
     *   name 字段 作key  value字段 作 value
     * 
     * **/
    public static function getConfigList(){
        
         //查询 设置
        $model = new Config();
        
        $configList = $model->find()->asArray()->all();
        
        $data = array();
        
        foreach($configList as $v){
            
            $data[$v['name']] = $v['value'];
                 
        }
        
        
        return $data;
        
    }
    /**
     * Displays a single Config model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Config model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Config();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Config model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate()
    {
      
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }
    
    
    
    
   

    /**
     * Deletes an existing Config model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Config model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Config the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Config::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    
    //设置主主题
   public function actionSetTheme(){

       $themeName = \Yii::$app->request->get("themeName");

       if(empty($themeName)){
           \Yii::$app->session->setFlash("error", "主题名不能为空");
           return $this->redirect(\yii\helpers\Url::toRoute("themes/index"));
       }
       
       //检测  $themeName 主题 名的是否合法
       if(!is_dir(dirname(\Yii::$app->basePath).DIRECTORY_SEPARATOR."frontend".DIRECTORY_SEPARATOR."views".DIRECTORY_SEPARATOR.$themeName)){
           \Yii::$app->session->setFlash("error", "主题的文件夹不存在:".dirname(\Yii::$app->basePath).DIRECTORY_SEPARATOR."frontend".DIRECTORY_SEPARATOR."views".DIRECTORY_SEPARATOR.$themeName);
           return $this->redirect(\yii\helpers\Url::toRoute("themes/index"));
       }
       
       $query = \Yii::$app->db->createCommand("update {{config}} set value='$themeName' where name='THEME'")->execute();
       
       if($query){
           
           \Yii::$app->session->setFlash("success", "主题设置成功");
       }else{
           
           \Yii::$app->session->setFlash("error", "设置主题失败,不能把主题设置为当前主题");
       }
       
       return $this->redirect(\yii\helpers\Url::toRoute("themes/index"));
       
   }
    
    
    
}
